package com.xiangwushuo.framework.activity.main

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.alibaba.android.arouter.facade.annotation.Route
import com.lib.common.base.mvvm.CommonViewModelActivity
import com.lib.common.constant.RouterPathConstant
import com.lib.common.entity.LoginEvent
import com.lib.common.entity.LogoutEvent
import com.lib.common.entity.SetMainSelecteTabEvent
import com.lib.common.manager.UpdateManager
import com.lib.framework.entity.Event
import com.lib.framework.manager.LogManager
import com.lib.framework.widget.SimpleFragmentPagerAdapter
import com.lib.framework.widget.WidgetUtil
import com.xiangwushuo.framework.R
import com.xiangwushuo.framework.activity.main.fragment.find.FindFragment
import com.xiangwushuo.framework.activity.main.fragment.home.HomeFragment
import com.xiangwushuo.framework.activity.main.fragment.msg.MsgFragment
import com.xiangwushuo.framework.activity.main.fragment.my.MyFragment
import com.xiangwushuo.framework.databinding.ActivityMainBinding
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe


/**
 * Copyright (C), 2019-2019
 * FileName: MainActivity
 * Author: Kevin
 * Date: 2019-12-31 11:23
 * Description:
 * History: 主页面
 * <author> <time> <version> <desc>
 * 作者姓名 修改时间 版本号 描述
 */
@Route(path = RouterPathConstant.PATH_MAIN)
class MainActivity : CommonViewModelActivity<MainViewModel>() {

    companion object {

        /**
         * 发给 activity 的事件
         */
        const val EVENT_XXX = 1 // XXX 事件

        const val PAGE_INDEX_HOME = 0 // 分页索引：首页
        const val PAGE_INDEX_FIND = 1 // 分页索引：发现
        const val PAGE_INDEX_MSG = 2 // 分页索引：消息
        const val PAGE_INDEX_MY = 3 // 分页索引：我的
    }

    private var mDataBinding: ActivityMainBinding? = null

    /**
     * tab 标签正常时的颜色
     */
    private var mTabNormalColor = 0x000000

    /**
     * tab 标签选中时的颜色
     */
    private var mTabSelectedColor = 0x000000

    /**
     * tab 正常时的icon
     */
    private val mTabIconNormalList = listOf(
        R.mipmap.ic_tab_1, R.mipmap.ic_tab_2, R.mipmap.ic_tab_3,
        R.mipmap.ic_tab_4
    )

    /**
     * tab 选中时的icon
     */
    private val mTabIconSelectedList = listOf(
        R.mipmap.ic_tab_1_selected,
        R.mipmap.ic_tab_2_selected, R.mipmap.ic_tab_3_selected, R.mipmap.ic_tab_4_selected
    )

    /**
     * 页面列表
     */
    private var mFragmentList = mutableListOf<Fragment>()

    /**
     * 页面适配器
     */
    private var mSimpleFragmentPagerAdapter = SimpleFragmentPagerAdapter(supportFragmentManager)

    /**
     * Tab当前选择的索引
     */
    private var mTabCurrentSelctedIndex = -1

    private val mHandler = Handler(Looper.getMainLooper())

    override fun getViewModelClass() = MainViewModel::class.java

    override fun onCreate(savedInstanceState: Bundle?) {
        mIsSetDefaultStatusBar = false
        super.onCreate(savedInstanceState)
        mDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        mDataBinding?.viewModel = mViewModel

        initView()
        EventBus.getDefault().register(this)

        mHandler.postDelayed({
            // 检测版本升级
            UpdateManager.checkVersion(this)
        }, 1000)
    }

    /**
     * 初始化视图
     */
    private fun initView() {
        mTabNormalColor = WidgetUtil.getColorFromRes(R.color.main_tab_text_normal)
        mTabSelectedColor = WidgetUtil.getColorFromRes(R.color.main_tab_text_selected)

        mDataBinding?.let { dataBinding ->

            mFragmentList.add(HomeFragment.newInstance("", ""))
            mFragmentList.add(FindFragment.newInstance("", ""))
            mFragmentList.add(MsgFragment.newInstance("", ""))
            mFragmentList.add(MyFragment.newInstance("", ""))

            mSimpleFragmentPagerAdapter.setFragmentList(mFragmentList)

            dataBinding.viewPager.adapter = mSimpleFragmentPagerAdapter
            dataBinding.viewPager.addOnPageChangeListener(mOnPageChangeListener)
            dataBinding.viewPager.setIsCanScroll(false)
            dataBinding.viewPager.offscreenPageLimit = 4

            dataBinding.bottomBar.clTab1.setOnClickListener {
                dataBinding.viewPager.setCurrentItem(0, false)
            }

            dataBinding.bottomBar.clTab2.setOnClickListener {
                dataBinding.viewPager.setCurrentItem(1, false)
            }

            dataBinding.bottomBar.clTab3.setOnClickListener {
                dataBinding.viewPager.setCurrentItem(2, false)
            }

            dataBinding.bottomBar.clTab4.setOnClickListener {
                dataBinding.viewPager.setCurrentItem(3, false)
            }


            val selectTabIndex = PAGE_INDEX_HOME
            dataBinding.viewPager.currentItem = selectTabIndex
            setSelectedTab(selectTabIndex)
        }
    }

    private var mOnPageChangeListener = object : ViewPager.OnPageChangeListener {
        override fun onPageScrollStateChanged(state: Int) {

        }

        override fun onPageScrolled(
            position: Int, positionOffset: Float,
            positionOffsetPixels: Int
        ) {

        }

        override fun onPageSelected(position: Int) {
            setSelectedTab(position)
        }
    }

    /**
     * 设置选中标签
     */
    private fun setSelectedTab(selectIndex: Int) {
        if (selectIndex < PAGE_INDEX_HOME || selectIndex > PAGE_INDEX_MY || mTabCurrentSelctedIndex == selectIndex) {
            return
        }

        // 还原之前选中的tab 为 未选中 样式
        when (mTabCurrentSelctedIndex) {
            PAGE_INDEX_HOME -> {
                mDataBinding?.bottomBar?.ivTab1?.setImageResource(
                    mTabIconNormalList[mTabCurrentSelctedIndex])
                mDataBinding?.bottomBar?.tvTab1?.setTextColor(mTabNormalColor)
            }

            PAGE_INDEX_FIND -> {
                mDataBinding?.bottomBar?.ivTab2?.setImageResource(
                    mTabIconNormalList[mTabCurrentSelctedIndex])
                mDataBinding?.bottomBar?.tvTab2?.setTextColor(mTabNormalColor)
            }

            PAGE_INDEX_MSG -> {
                mDataBinding?.bottomBar?.ivTab3?.setImageResource(
                    mTabIconNormalList[mTabCurrentSelctedIndex])
                mDataBinding?.bottomBar?.tvTab3?.setTextColor(mTabNormalColor)
            }

            PAGE_INDEX_MY -> {
                mDataBinding?.bottomBar?.ivTab4?.setImageResource(
                    mTabIconNormalList[mTabCurrentSelctedIndex])
                mDataBinding?.bottomBar?.tvTab4?.setTextColor(mTabNormalColor)
            }
        }

        mTabCurrentSelctedIndex = selectIndex

        // 设置 选中 样式
        when (mTabCurrentSelctedIndex) {
            PAGE_INDEX_HOME -> {
                mDataBinding?.bottomBar?.ivTab1?.setImageResource(
                    mTabIconSelectedList[mTabCurrentSelctedIndex])
                mDataBinding?.bottomBar?.tvTab1?.setTextColor(mTabSelectedColor)
            }

            PAGE_INDEX_FIND -> {
                mDataBinding?.bottomBar?.ivTab2?.setImageResource(
                    mTabIconSelectedList[mTabCurrentSelctedIndex])
                mDataBinding?.bottomBar?.tvTab2?.setTextColor(mTabSelectedColor)
            }

            PAGE_INDEX_MSG -> {
                mDataBinding?.bottomBar?.ivTab3?.setImageResource(
                    mTabIconSelectedList[mTabCurrentSelctedIndex])
                mDataBinding?.bottomBar?.tvTab3?.setTextColor(mTabSelectedColor)
            }

            PAGE_INDEX_MY -> {
                mDataBinding?.bottomBar?.ivTab4?.setImageResource(
                    mTabIconSelectedList[mTabCurrentSelctedIndex])
                mDataBinding?.bottomBar?.tvTab4?.setTextColor(mTabSelectedColor)
            }
        }

    }

    override fun dealEvent(event: Event?): Boolean {
        // 处理 viewModel 发送过来的事件
        when (event?.code) {
            EVENT_XXX -> {
                val extraObj = event.extraObj
                if (extraObj is String) {
                    LogManager.i(mTag, "XXX 事件 的额外参数 extraObj = $extraObj")
                }
                return true
            }
        }

        return super.dealEvent(event)
    }

    override fun onDestroy() {
        super.onDestroy()
        mHandler.removeCallbacksAndMessages(null)
        EventBus.getDefault().unregister(this)
    }


    @Subscribe
    fun onLoginEvent(obj: LoginEvent) { // 登陆

    }

    @Subscribe
    fun onLogoutEvent(obj: LogoutEvent) { // 登出

    }

    @Subscribe
    fun onSetMainSelecteTabEvent(obj: SetMainSelecteTabEvent) { // 设置主页选择tab 事件
        if (obj.tabIndex in 0..3) {
            mDataBinding?.viewPager?.currentItem = obj.tabIndex
        }
    }

}
